package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.client.ArticleFeign;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.article.dtos.AuthorDto;
import com.heima.model.media.dtos.WmUserDto;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.dtos.UserAuthDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserAuth;
import com.heima.user.mapper.ApUserAuthMapper;
import com.heima.user.service.ApUserAuthService;
import com.heima.user.service.ApUserService;
import com.heima.wemedia.client.WemediaFeign;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-04-27
 */
@Slf4j
@Service
public class ApUserAuthServiceImpl extends ServiceImpl<ApUserAuthMapper, ApUserAuth> implements ApUserAuthService {

    /**
     * 分页查询
     * @param dto
     * @return
     */
    @Override
    public PageResult<UserAuthDto> findAuthByPage(AuthDto dto) {
//        设置分页
        IPage<ApUserAuth> iPage = new Page<>(dto.getPage(),dto.getSize());
//        设置条件
        LambdaQueryWrapper<ApUserAuth> queryWrapper = new LambdaQueryWrapper<>();
        if(dto.getStatus() != null){
            queryWrapper.eq(ApUserAuth::getStatus,dto.getStatus());
        }
//        分页查询
        IPage<ApUserAuth> userAuthIPage = page(iPage, queryWrapper);
        if(userAuthIPage==null || CollectionUtils.isEmpty(userAuthIPage.getRecords())){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        构造返回对象
        List<UserAuthDto> authDtoList = BeanHelper.copyWithCollection(userAuthIPage.getRecords(), UserAuthDto.class);
        return new PageResult<>(dto.getPage(),dto.getSize(),userAuthIPage.getTotal(),authDtoList);
    }

    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private ApUserService apUserService;
    /**
     * 认证通过
     * @param dto
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void authUser(AuthDto dto, int status) {

        ApUserAuth apUserAuth = new ApUserAuth();
        apUserAuth.setId(dto.getId());
        apUserAuth.setStatus(status);
        if(status==2) {
            apUserAuth.setReason(dto.getMsg());
        }
//        修改用户认证状态
        boolean b = this.updateById(apUserAuth);
        if(!b){
            log.error("修改认证状态失败，id={}",dto.getId());
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
//        如果不通过直接返回
           if(status==2){
               log.info("认证不通过，返回，id={}",dto.getId());
               return ;
           }
//           查询auth表
        apUserAuth = getById(dto.getId());
        Integer apUserId = apUserAuth.getUserId();
//           查询apUser表
        ApUser apUser = apUserService.getById(apUserId);
//        远程调用自媒体服务，创建自媒体用户
        WmUserDto wmUserDto = new WmUserDto();
           wmUserDto.setApUserId(apUserId);
           wmUserDto.setName(apUser.getName());
           wmUserDto.setPassword(apUser.getPassword());
           wmUserDto.setStatus(9);
           wmUserDto.setPhone(apUser.getPhone());
           try{
               Integer wmUserId = wemediaFeign.saveWmUser(wmUserDto);
               wmUserDto.setId(wmUserId);
           }catch (Exception e){
               e.printStackTrace();
               log.error("远程调用自媒体服务异常");
               throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
           }

//        远程调用文章服务，创建作者
        AuthorDto authorDto = new AuthorDto();
        authorDto.setUserId(apUserId);
        authorDto.setWmUserId(wmUserDto.getId());
        authorDto.setName(apUser.getName());
        authorDto.setType(2);
        try {
            Integer authorId = articleFeign.saveAuthor(authorDto);
        }catch(Exception e){
            e.printStackTrace();
            log.error("远程调用创建作者失败");
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }

//        修改当前用户的类型 flag改为1
        apUser = new ApUser();
        apUser.setId(apUserId);
        apUser.setFlag(1);
        boolean b1 = apUserService.updateById(apUser);
        if(!b1){
            log.error("更新用户flag失败，apUserId={}",apUserId);
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
